package controls

import (
	"github.com/labstack/echo/v4"
	"github.com/rs/xid"
	"sofuny/models"
	"sofuny/utils"
	"time"
)

// 添加邮箱
func AddSubscribe(ctx echo.Context) error {
	var v utils.Value
	var subscribe models.Subscribe
	// 绑定数据
	if err := ctx.Bind(&v); err != nil {
		return ctx.JSON(200, utils.Response{
			Code:  201,
			Msg:   utils.DataBindErrorMessage,
			Data:  err.Error(),
			Total: 0,
			Time:  utils.FormatTime(),
		})
	}
	// 判断数据
	if v.Email == ""  || v.SubscribeType == ""{
		return ctx.JSON(200, utils.Response{
			Code:  201,
			Msg:   utils.DataEmptyMessage,
			Data:  nil,
			Total: 0,
			Time:  utils.FormatTime(),
		})
	}
	// 添加
	subscribe.CreateAt = time.Now().Local()
	subscribe.UpdateAt = subscribe.CreateAt
	subscribe.Uuid = xid.New().String()
	subscribe.Status = false
	subscribe.Email = v.Email
	subscribe.Type = v.SubscribeType

	if err := db.Create(&subscribe).Error; err != nil {
		return ctx.JSON(200, utils.Response{
			Code:  201,
			Msg:   "创建订阅失败",
			Data:  err,
			Total: 0,
			Time:  utils.FormatTime(),
		})
	}
	// 成功
	// TODO 验证邮箱的可行性 发送一封验证邮箱
	return ctx.JSON(200, utils.Response{
		Code:  200,
		Msg:   utils.DataSuccessMessage,
		Data:  nil,
		Total: 0,
		Time:  utils.FormatTime(),
	})
}
